package com.ks.api.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ks.api.entity.KsConfigSc;
import com.ks.api.mapper.KsConfigScMapper;
import com.ks.api.service.KuaishouTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
public class TestController {
    
    @Autowired
    private KuaishouTokenService kuaishouTokenService;
    
    @Autowired
    private Environment environment;

    @Autowired
    private KsConfigScMapper ksConfigScMapper;

    
    private static final String KS_API_URL = "https://ad.e.kuaishou.com/rest/openapi/v1/creative/preview";

    @GetMapping("/test")
    public String test() {
        return "API is working!";
    }

    @GetMapping("/cili/callback")
    public String handleCallback(
            @RequestParam("auth_code") String authCode,
            @RequestParam("state") String state)
    {

        // 通知TokenService收到了新的auth_code，state参数作为应用标号(appDh)
        kuaishouTokenService.onAuthCodeReceived(state, authCode);
        
        // 返回响应
        return "Callback received with auth_code: " + authCode + " and state: " + state;
    }
    
    @GetMapping("/getUserData")
    public ResponseEntity<Map<String, Object>> getUserData(
            @RequestParam(value = "kuaishouId", required = false) String kuaishouId,
            @RequestParam(value = "phoneNumber", required = false) String phoneNumber,
            @RequestParam(value = "appId", required = true) String appId) {
        
        // 验证至少提供了一个参数
        if ((kuaishouId == null || kuaishouId.isEmpty()) && 
            (phoneNumber == null || phoneNumber.isEmpty())) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "必须提供快手ID或手机号");
            return ResponseEntity.badRequest().body(error);
        }
        
        // 模拟获取用户数据
        Map<String, Object> userData = new HashMap<>();
        userData.put("success", true);
        
        Map<String, Object> data = new HashMap<>();
        if (kuaishouId != null && !kuaishouId.isEmpty()) {
            data.put("kuaishouId", kuaishouId);
            data.put("nickname", "用户_" + kuaishouId);
        } else {
            data.put("phoneNumber", phoneNumber);
            data.put("nickname", "用户_" + phoneNumber.substring(phoneNumber.length() - 4));
        }
        
        data.put("appId", appId);
        data.put("level", 5);
        data.put("coins", 1000);
        data.put("registerDate", "2023-01-01");
        
        userData.put("data", data);
        
        return ResponseEntity.ok(userData);
    }
    
    /**
     * 获取JSON文件内容
     * 先尝试从根目录读取，如果失败则尝试从resources目录读取
     */
    private String getAppDataJson() throws IOException {
        Path path = Paths.get("app_data.json");
        return new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
    }
    
    /**
     * 获取应用列表
     */
    @GetMapping("/getAppList")
    public ResponseEntity<List<Map<String, Object>>> getAppList() {
        try {
            // 获取app_data.json的内容
            String jsonContent = getAppDataJson();
            
            JSONArray jsonArray = JSONUtil.parseArray(jsonContent);
            List<Map<String, Object>> appList = new ArrayList<>();
            
            // 只返回应用ID和名称给前端
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject app = jsonArray.getJSONObject(i);
                Map<String, Object> appInfo = new HashMap<>();
                appInfo.put("id", app.getStr("advertiser_id"));
                appInfo.put("name", app.getStr("appName"));
                appList.add(appInfo);
            }
            
            return ResponseEntity.ok(appList);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }
    
    @PostMapping("/pushDataToKuaishou")
    public ResponseEntity<Map<String, Object>> pushDataToKuaishou(
            @RequestBody Map<String, Object> requestData) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 从请求中获取数据
            String appId = String.valueOf(requestData.get("appId"));
            String searchType = String.valueOf(requestData.get("searchType"));
            String value = String.valueOf(requestData.get("value"));
            
            // 验证参数
            if (appId == null || appId.isEmpty()) {
                response.put("code", 1);
                response.put("message", "应用ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (value == null || value.isEmpty()) {
                response.put("code", 1);
                response.put("message", "快手ID或手机号不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 获取app_data.json中对应的应用详情
            String jsonContent = getAppDataJson();
            JSONArray jsonArray = JSONUtil.parseArray(jsonContent);
            
            JSONObject appData = null;
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject app = jsonArray.getJSONObject(i);
                if (appId.equals(app.getStr("advertiser_id"))) {
                    appData = app;
                    break;
                }
            }
            
            if (appData == null) {
                response.put("code", 1);
                response.put("message", "找不到对应的应用信息");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 构建请求参数
            JSONObject requestParams = new JSONObject();
            requestParams.set("advertiser_id", appData.getStr("advertiser_id"));
            requestParams.set("unit_type", 4);  // 固定为4: 自定义创意
            
            if (appData.containsKey("creative_id") && !appData.getStr("creative_id", "").isEmpty()) {
                requestParams.set("creative_id", appData.getStr("creative_id"));
            }
            
            // 根据searchType设置user_ids或phones
            if ("kuaishouId".equals(searchType)) {
                List<String> userIds = new ArrayList<>();
                userIds.add(value);
                requestParams.set("user_ids", userIds);
            } else {
                List<String> phones = new ArrayList<>();
                phones.add(value);
                requestParams.set("phones", phones);
            }
            
            LambdaQueryWrapper<KsConfigSc> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(KsConfigSc::getAdvertiserId,appData.getStr("advertiser_id"));
            KsConfigSc ksConfigSc = ksConfigScMapper.selectOne(wrapper);
            String accessToken = kuaishouTokenService.getAccessToken(ksConfigSc.getAppDh());
            // 调用快手API
            HttpResponse execute = HttpRequest.post(KS_API_URL)
                    .body(JSON.toJSONString(requestParams))
                    .header("Content-Type", "application/json")
                    .header("Access-Token", accessToken)
                    .execute();
            
            // 获取并解析响应内容
            String body = execute.body();

            // 解析API响应
            JSONObject apiResponse = JSONUtil.parseObj(body);
            
            // 只返回code和message
            response.put("code", apiResponse.getInt("code", 1));
            response.put("message", apiResponse.getStr("message", "未知错误"));
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            e.printStackTrace();
            response.put("code", 1);
            response.put("message", "推送数据时发生异常: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}